<template>
	<view class="content">
		<view class="container">
			<!-- 消息列表标题 -->
			<view style="text-align: center;font-size: 20px;font-weight: 600;margin-top: 10px;margin-bottom: 10px;">
				消息列表
			</view>

			<!-- 消息项 -->
			<view
				style="border-radius: 10px;margin-left: 2%; border: 1px solid slategray;;width: 96%;margin-bottom:15px;height: 100px;box-sizing: border-box;padding:10rpx 40rpx;box-sizing:border-box;display: flex;justify-content: flex-start;align-items: center;;height: 160rpx;"
				v-for="(message, index) in messages" :key="index">

				<view style="width: 17%;">
					<image style="width: 50px; height: 50px; background-color: #eeeeee;" :src="message.headimgurl">
					</image>
				</view>
				<view style="display: block;width: 80%;height:50px;display:  flex;;justify-content: space-between;">
					<view style="width: 50%;height: 50px;">
						<h5>{{message.comName}}</h5>
						<p>{{message.tel}}</p>
					</view>
					<view style="width: 50%;height: 50px;display: flex;align-items: center;justify-content: center;">
						<span style="color: gainsboro;font-size: 12px;">{{message.starttime}}</span>
					</view>
				</view>

			</view>
		<view style="width: 40%;box-sizing: border-box;padding: 20px 10rpx;margin: auto;">
			<uni-section title="默认样式" type="line" padding>
				<uni-pagination :current="form.current" :total="form.total" title="标题文字" @change=change />
			</uni-section>
		</view>
		</view>
	</view>
</template>

<script>
	import io from 'socket.io-client';

	export default {
		data() {
			return {
				apiserver: '',
				headimgurl: "",
				socket: null, // Socket.io连接对象
				messages: ['暂无信息'], // 消息列表
				callStartTime: null, // 通话开始时间
				callEndTime: null, // 通话结束时间
				isInCall: false, // 通话状态
				token: '',
				form: {
					current: 1,
					pageSize: 10,
					total:0
				}

			};
		},
		methods: {
			change(e){
		if(e.type=='next'){
				this.form.current=this.form.current+1
		}else{
				this.form.current=this.form.current-1
		}
				this.getFollowcallmy()
			},
			// 返还给后台数据
			addFollowCall(data) {
				let that = this
				uni.request({
					url: 'http://192.168.1.22/api/addFollowcall', // 例如: 'https://example.com/api/addFollowcall'
					method: 'POST', // 根据你的API需求选择GET或POST
					data: {
						tel: that.tel,
						comName: that.comName,
						starttime: that.callStartTime,
						endtime: that.callEndTime,
						comCode: that.comCode,
						token: that.token
					}, // 你要发送的数据

					success: (res) => {
						console.log('添加成功:', res.data);
						// 在这里处理成功后的逻辑
					},
					fail: (err) => {
						console.error('添加失败:', err);
						// 在这里处理失败后的逻辑
					}
				});
			},
			// 获取通话记录
			getFollowcallmy() {
				this.messages=[]
				console.log(4991966,this.messages)
				let form = {
					pageNo: this.form.current,
					pageSize: this.form.pageSize,
					token: this.token

				}
console.log(888888888,form)
				let that = this
				uni.request({
					url: that.apiserver + '/api/getFollowcallmy', // 例如: 'https://example.com/api/addFollowcall'
					method: 'GET', // 根据你的API需求选择GET或POST
					data: form, // 你要发送的数据

					success: (res) => {
						console.log(1112233444555677, res)
						let list = []
						res.data.data.list.map((x, index) => {
							x.headimgurl = that.headimgurl + '?t=' + x.comName
							list.push(x)
						})
						
						that.form.total=res.data.data.total
						that.messages = list;
						console.log('list', that.form)
						// 在这里处理成功后的逻辑
					},
					fail: (err) => {
						console.error('添加失败:', err);
						// 在这里处理失败后的逻辑
					}
				});
			},
			// 设置Socket连接
			setupSocket(option) {
				console.log(111)
				var that = this;
				const server = "ws://" + option.server; // 后端服务器地址
				const token = option.token; // 用户token
				that.token = token
				that.apiserver = option.apiserver
				that.headimgurl = option.headimgurl

				if (that.token && that.apiserver) {
					that.messages = []
					that.getFollowcallmy()
				}

				// 初始化Socket连接
				that.socket = io(server, {
					autoConnect: false,
				});

				// 连接成功的处理
				that.socket.on('connect', () => {
					console.log('Socket.io 连接已建立');
					that.socket.emit('login', token); // 向服务器发送登录信息
				});

				// 处理接收到的新消息
				that.socket.on('new_msg', (data) => {
					console.log('收到服务器消息:', data);
					let result = data.split("||");
					that.tel = result[0]
					that.comCode = result[1]
					that.comName = result[2]

					that.startCall(that.tel); // 开始拨打电话
				});

				// 处理连接断开的情况
				that.socket.on('disconnect', () => {
					console.log('Socket.io 连接已断开');
				});

				// 处理连接错误
				that.socket.on('connect_error', (err) => {
					console.error('连接错误', err);
					setTimeout(() => {
						that.socket.connect();
					}, 2000); // 2秒后重新连接
				});

				// 处理其他错误
				that.socket.on('error', (err) => {
					console.error('Socket.io 错误', err);
				});

				// 手动连接服务器
				that.socket.connect();
			},

			// 开始拨打电话
			startCall(phoneNumber) {
				const that = this;
				that.callStartTime = new Date(); // 记录开始时间
				that.isInCall = true; // 标记通话状态
				uni.makePhoneCall({
					phoneNumber: phoneNumber,
					success: function() {
						console.log('Call started successfully.');
					},
					fail: function(err) {
						console.log('Failed to start the call:', err);
						that.isInCall = false; // 如果拨打失败，重置通话状态
					}
				});
			}
		},

		// 页面挂载时从本地存储中获取数据并建立Socket连接
		mounted() {
			let that = this;
			uni.getStorage({
				key: 'barcode',
				success: function(res) {
					console.log('提取的数据为', res.data);
					that.setupSocket(res.data);
				}
			});

		},

		// 当页面隐藏时记录开始时间
		onHide() {
			if (this.isInCall) {
				console.log('App is in background (during call)');
				this.callStartTime = this.callStartTime || new Date();
			}
		},

		// 当页面显示时记录结束时间并计算通话时长，同时将数据传给服务器
		onShow() {
			if (this.isInCall) {
				console.log('App is in foreground (call ended)');
				this.callEndTime = new Date(); // 记录结束时间
				const duration = (this.callEndTime - this.callStartTime) / 1000; // 计算通话时长
				console.log('Call duration: ' + duration + ' seconds');
				this.isInCall = false; // 重置通话状态

				// 将通话时长数据传给服务器
				if (this.socket) {
					this.addFollowCall()
					this.getFollowcallmy()
				}
			}
		},

		// 页面销毁前关闭Socket连接
		beforeDestroy() {
			if (this.socket) {

				this.socket.disconnect();
			}
		}
	};
</script>

<style scoped>
	.content {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		width: 100vw;
		padding-bottom: 10px;
	}

	.container {
		width: 100%;
		height: 100%;
	}

	button {
		display: block;
		padding: 10px 20px;
		background-color: #007AFF;
		color: white;
		border: none;
		border-radius: 5px;
	}
</style>